var table_data;
var realdata;
var editIndex = undefined;
var toolbar = [{
    text:'Add',
    iconCls:'icon-add',
    handler:function(){
        append();
    }
},{
    text:'Delete',
    iconCls:'icon-remove',
    handler:function(){
        removeit();
    }
},'-',{
    text:'Save',
    iconCls:'icon-save',
    handler:function(){
        var effectdata = new Object();
        effectRow = $('#dg').datagrid('getChanges', "inserted");
        if(effectRow.length){
            effectdata['inserted'] = JSON.stringify(effectRow);
        }
        
        effectRow = $('#dg').datagrid('getChanges', "deleted");
        if(effectRow.length){
            effectdata['deleted'] = JSON.stringify(effectRow);
        }

        effectRow = $('#dg').datagrid('getChanges', "updated");
        if(effectRow.length){
            effectdata['updated'] = JSON.stringify(effectRow);
        }

        $.ajax({
          url: "post",
          type:"post",         
          dataType:"text",
          data: effectdata,
          success:function(data){
              alert(data);
          }
        });
    }
}];

function append(){
    if (endEditing()){
        $('#dg').datagrid('appendRow',{SYSTEM_TYPE:1});
        editIndex = $('#dg').datagrid('getRows').length-1;
        $('#dg').datagrid('selectRow', editIndex)
        $('#dg').datagrid('beginEdit', editIndex);
    }
}

function removeit(){
    if (editIndex == undefined){return}
    $('#dg').datagrid('cancelEdit', editIndex)
    $('#dg').datagrid('deleteRow', editIndex);
    editIndex = undefined;
}

$(function () {

})

$.extend($.fn.datagrid.methods, {
    editCell: function(jq,param){
        return jq.each(function(){
            var opts = $(this).datagrid('options');
            var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
            for(var i=0; i<fields.length; i++){
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] != param.field){
                    col.editor = null;
                }
            }
            $(this).datagrid('beginEdit', param.index);
            for(var i=0; i<fields.length; i++){
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }
        });
    }
});

function endEditing(){
    if (editIndex == undefined){return true}
    if ($('#dg').datagrid('validateRow', editIndex)){
        $('#dg').datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}

function onClickCell(index, field){
    if (endEditing()){
        $('#dg').datagrid('selectRow', index)
        $('#dg').datagrid('editCell', {index:index,field:field});
        editIndex = index;
    }
}